{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 张量\n",
    "\n",
    "[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/tutorials/source_zh_cn/tensor.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/quick_start/mindspore_tensor.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9vYnMuZHVhbHN0YWNrLmNuLW5vcnRoLTQubXlodWF3ZWljbG91ZC5jb20vbWluZHNwb3JlLXdlYnNpdGUvbm90ZWJvb2svbW9kZWxhcnRzL3F1aWNrX3N0YXJ0L21pbmRzcG9yZV90ZW5zb3IuaXB5bmI=&imagename=MindSpore1.1.1)\n",
    "\n",
    "张量（Tensor）是MindSpore网络运算中的基本数据结构。\n",
    "\n",
    "首先导入本文档需要的模块和接口，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from mindspore import Tensor, context\n",
    "from mindspore import dtype as mstype\n",
    "context.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 初始化张量\n",
    "\n",
    "张量的初始化方式有多种，构造张量时，支持传入`Tensor`、`float`、`int`、`bool`、`tuple`、`list`和`NumPy.array`类型。\n",
    "\n",
    "- **根据数据直接生成**\n",
    "\n",
    "可以根据数据创建张量，数据类型可以设置或者自动推断。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Tensor(0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- **从NumPy数组生成**\n",
    "\n",
    "可以从NumPy数组创建张量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "arr = np.array([1, 0, 1, 0])\n",
    "x_np = Tensor(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "初始值是`NumPy.array`，则生成的`Tensor`数据类型与之对应。\n",
    "\n",
    "- **继承另一个张量的属性，形成新的张量**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 1]\n",
      " [1 1]]\n"
     ]
    }
   ],
   "source": [
    "from mindspore import ops\n",
    "oneslike = ops.OnesLike()\n",
    "x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))\n",
    "output = oneslike(x)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- **输出指定大小的恒定值张量**\n",
    "\n",
    "`shape`是张量的尺寸元组，确定输出的张量的维度。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1. 1.]\n",
      " [1. 1.]]\n",
      "[[0. 0.]\n",
      " [0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "from mindspore.ops import operations as ops\n",
    "\n",
    "shape = (2, 2)\n",
    "ones = ops.Ones()\n",
    "output = ones(shape, mstype.float32)\n",
    "print(output)\n",
    "\n",
    "zeros = ops.Zeros()\n",
    "output = zeros(shape, mstype.float32)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "`Tensor`初始化时，可指定dtype，如`mstype.int32`、`mstype.float32`、`mstype.bool_`等。\n",
    "\n",
    "## 张量的属性\n",
    "\n",
    "张量的属性包括形状（shape）和数据类型（dtype）。\n",
    "\n",
    "- 形状：`Tensor`的shape，是一个tuple。\n",
    "- 数据类型：`Tensor`的dtype，是MindSpore的一个数据类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Datatype of tensor: Float32\n",
      "Shape of tensor: (1, 2, 3)\n"
     ]
    }
   ],
   "source": [
    "t1 = Tensor(np.zeros([1,2,3]), mstype.float32)\n",
    "print(\"Datatype of tensor: {}\".format(t1.dtype))\n",
    "print(\"Shape of tensor: {}\".format(t1.shape))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 张量运算\n",
    "\n",
    "张量之间有很多运算，包括算术、线性代数、矩阵处理（转置、标引、切片）、采样等，下面介绍其中几种操作，张量运算和NumPy的使用方式类似。\n",
    "\n",
    "类似NumPy的索引和切片操作：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First row: [0. 1.]\n",
      "First column: [0. 2.]\n",
      "Last column: [1. 3.]\n"
     ]
    }
   ],
   "source": [
    "tensor = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n",
    "print(\"First row: {}\".format(tensor[0]))\n",
    "print(\"First column: {}\".format(tensor[:, 0]))\n",
    "print(\"Last column: {}\".format(tensor[..., -1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "`Concat`将给定维度上的一系列张量连接起来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0. 1.]\n",
      " [2. 3.]\n",
      " [4. 5.]\n",
      " [6. 7.]]\n"
     ]
    }
   ],
   "source": [
    "data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n",
    "data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))\n",
    "op = ops.Concat()\n",
    "output = op((data1, data2))\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "`Stack`则是从另一个维度上将两个张量合并起来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0. 1.]\n",
      "  [2. 3.]]\n",
      "\n",
      " [[4. 5.]\n",
      "  [6. 7.]]]\n"
     ]
    }
   ],
   "source": [
    "data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))\n",
    "data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))\n",
    "op = ops.Stack()\n",
    "output = op([data1, data2])\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "普通运算："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 4. 10. 18.]\n"
     ]
    }
   ],
   "source": [
    "input_x = Tensor(np.array([1.0, 2.0, 3.0]), mstype.float32)\n",
    "input_y = Tensor(np.array([4.0, 5.0, 6.0]), mstype.float32)\n",
    "mul = ops.Mul()\n",
    "output = mul(input_x, input_y)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 与NumPy转换\n",
    "\n",
    "张量可以和NumPy进行互相转换。\n",
    "\n",
    "### 张量转换为NumPy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "output: <class 'mindspore.common.tensor.Tensor'>\n",
      "n_output: <class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "zeros = ops.Zeros()\n",
    "output = zeros((2,2), mstype.float32)\n",
    "print(\"output: {}\".format(type(output)))\n",
    "n_output = output.asnumpy()\n",
    "print(\"n_output: {}\".format(type(n_output)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### NumPy转换为张量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "output: <class 'numpy.ndarray'>\n",
      "t_output: <class 'mindspore.common.tensor.Tensor'>\n"
     ]
    }
   ],
   "source": [
    "output = np.array([1, 0, 1, 0])\n",
    "print(\"output: {}\".format(type(output)))\n",
    "t_output = Tensor(output)\n",
    "print(\"t_output: {}\".format(type(t_output)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
